<template>
  <div class="new-notice">
    <nav-header>
      <template slot="menuBefore">
        <li>
          <router-link to="/portal/show/dress-up" tag="a">装扮管理</router-link>
        </li>
        <li class="gap">&gt;</li>
      </template>
      <li>{{title}}</li>
    </nav-header>
    <div class="new-notice-c" v-loading="loading.status" :element-loading-text="loading.txt">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题" prop="name">
          <el-input v-model.trim="ruleForm.name" placeholder="请输入标题" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="封面图片" prop="picture">
          <uploader-dom :options="uploadOptions" :picture="ruleForm.picture" @imgListen="getImg"></uploader-dom>
        </el-form-item>
        <el-form-item label-width="0" required>
          <el-col :span="11">
            <el-form-item label="公告分类" prop="category_id">
              <el-select
                v-model="ruleForm.category_id"
                filterable
                placeholder="请选择活动分类"
                v-if="cateData.length > 0"
              >
                <template v-for="(item,inx) in cateData">
                  <el-option
                    v-if="parseInt(item.status) === 1"
                    :label="item.name"
                    :value="item.id"
                    :key="inx"
                  ></el-option>
                </template>
              </el-select>

              <div v-else class="category-tip">
                <span>暂无分类，请先添加公告分类哦~</span>
                <a @click="addNotice">
                  <i class="el-icon-plus"></i>立即添加
                </a>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label=" 状态" prop="state">
              <el-select v-model="ruleForm.status" filterable placeholder="请选择活动区域">
                <el-option label="开启" value="1"></el-option>
                <el-option label="关闭" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="公告排序" prop="sort" class="page-mb">
          <el-input-number v-model="ruleForm.sort" :min="0" :max="100" :precision="0" label="公告排序"></el-input-number>
          <span>根据设置数字的大小，数字越大新闻排的越往后</span>
        </el-form-item>
        <el-form-item label="公告内容" prop="content" class="notice-content">
          <tinymce
            id="d1"
            :plugins="plugins"
            :other_options="options"
            :toolbar1="toolbar1"
            :toolbar2="toolbar2"
            :images_upload_handler="images_upload_handler"
            v-model.trim="ruleForm.content"
            @editorInit="editorInit"
          ></tinymce>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" plain @click="resetForm('ruleForm')" type="primary">重置</el-button>
          <el-button size="medium" type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import tinymce from "vue-tinymce-editor";
import axios from "../../../tools/axios";
import uploaderDom from "@/components/common/uploader-image";

export default {
  data() {
    return {
      loading: {
        status: false,
        txt: "获取数据...",
      },
      title: "添加公告",
      cateData: [],
      uploadInfo: {
        file_name: "",
        file_path: "",
        file_size: 0,
      },
      attrs: {
        accept: ["image/*"],
      },
      uploadOptions: {
        target: this.BASE_URL + "/api/resource/res_upload",
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
      },
      plugins: ["paste", "fullscreen", "link", "image"],
      toolbar1: "paste,fullscreen,link",
      toolbar2:
        "table |insertfile undo redo | formatselect  | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | link | image | removeformat",
      options: {
        images_upload_handler: this.images_upload_handler,
        language_url: "/static/tinymce_languages/zh_CN.js",
        images_upload_url: this.BASE_URL + "/api/resource/res_upload_permanent",
        paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
        paste_convert_word_fake_lists: false, // 插入word文档需要该属性
        paste_webkit_styles: "all",
        paste_merge_formats: true,
        nonbreaking_force_tab: false,
        paste_auto_cleanup_on_paste: false,
        convert_urls: false,
        font_formats: `
                        微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                        宋体='宋体',Helvetica,Arial,sans-serif;
                        仿宋='仿宋',Helvetica,Arial,sans-serif;
                        楷体='楷体',Helvetica,Arial,sans-serif;
                        黑体='黑体',Helvetica,Arial,sans-serif;
                        幼圆='幼圆',Helvetica,Arial,sans-serif;
                        隶书='隶书',Helvetica,Arial,sans-serif;
                        华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                        苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                        Arial='Arial',Helvetica,Arial,sans-serif;
                        Verdana=verdana,geneva;
                        Webdings=webdings
                    `,
      },
      categoryParam: {
        status: 1,
      },
      ruleForm: {
        id: 0,
        name: "",
        picture: "",
        category_id: "",
        status: "1",
        sort: 50,
        content: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 3,
            max: 30,
            message: "长度在 3 到 30 个字符",
            trigger: "blur",
          },
          {
            pattern: this.rules.spaceKey.reg,
            message: this.rules.spaceKey.msg,
            trigger: "blur",
          },
        ],
        category_id: [
          { required: true, message: "请选择分类", trigger: "change" },
        ],
        sort: [
          { required: true, message: "请输入0~100的数字", trigger: "blur" },
        ],
        content: [
          {
            validator: this.checkContent,
            trigger: ["blur", "change"],
            required: true,
          },
        ],
      },
    };
  },
  created() {
    this.getCategory();
    if (!is_empty(this.$route.params.id)) {
      this.title = "编辑公告";
      this.getNewsInfo();
    }
  },
  methods: {
    addNotice() {
      this.$store.commit("SET_ACTIVEPANEL", "notice");
      this.$router.push("/portal/show/dress-up");
    },
    /**
     * 编辑器初始化
     */
    editorInit() {
      // 修改输入框内文字与边界的宽
      let dom = document
        .getElementById("d1_ifr")
        .contentWindow.document.getElementById("tinymce");
      dom.style.margin = "8px 25px 45px";
    },
    /**
     * 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
     */
    images_upload_handler(blobInfo, success, failure) {
      if (blobInfo.blob().type.indexOf("image/") === -1) {
        failure("只允许上传图片格式的文件");
      } else if (blobInfo.blob().size > 10240000) {
        failure("图片大小不能超过10M");
      } else {
        let formData = new FormData();
        formData.append("file", blobInfo.blob(), blobInfo.filename());
        let succ = (data) => {
          success(this.BASE_URL + data.data.data.file_path);
        };
        let fail = (data) => {
          // data.data =  data.data.data;
          failure(data.data.data.message);
        };
        //******************************TODO 不知为何要重新create*****************//
        const instance = axios.create({
          headers: {
            Authorization: `Bearer ${this.$g.access_token}`,
            DecisionPlatform: ` ${this.$g.access_token}`,
            token: sessionStorage.getItem("token"),
          },
          withCredentials: true,
        });
        instance
          .post("api/resource/res_upload_permanent", formData)
          .then(succ)
          .catch(fail);
      }
    },
    /**
     * 验证输入内容
     */
    checkContent(rule, value, callback) {
      if (!isEmpty(value)) {
        return callback(new Error("请填写内容"));
      } else {
        callback();
      }
    },
    getNewsInfo() {
      this.loading.status = true;
      this.loading.txt = "获取数据...";
      // 重写成功回调
      let success = (data) => {
        this.loading.status = false;
        this.ruleForm = {
          id: this.$route.params.id,
          name: data.data.name,
          picture: data.data.picture,
          content: data.data.content,
          sort: data.data.sort,
          status: data.data.status.toString(),
          category_id: data.data.category_id,
        };
      };
      let fail = (data) => {
        this.loading.status = false;
        $this.$message.error(data.msg);
      };
      this.$ajax.get("api/news/news_detail", {
        params: { id: this.$route.params.id },
        func: { success: success, fail: fail },
      });
    },
    saveNews() {
      let success = (data) => {
        this.loading.status = false;
        this.$message.success(data.msg);
        //设置activePanel
        this.$store.commit("SET_ACTIVEPANEL", "notice");

        setTimeout(() => {
          this.$router.push("/portal/show/dress-up");
        }, 1000);
      };

      if (parseInt(this.ruleForm.id) > 0) {
        this.$ajax.put("api/news/news", this.ruleForm, {
          func: { success: success },
        });
      } else {
        this.$ajax.post("api/news/news", this.ruleForm, {
          func: { success: success },
        });
      }
    },
    getCategory() {
      // 重写成功回调
      let success = (data) => {
        this.cateData = data.data;
      };
      this.$ajax.get("api/news/category", {
        params: this.categoryParam,
        func: { success: success },
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading.status = true;
          this.loading.txt = "保存数据...";
          this.saveNews();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getImg(mess) {
      this.ruleForm.picture = mess ? mess.file_path : "";
    },
  },
  components: {
    tinymce,
    uploaderDom,
  },
};
</script>

<style lang="scss">
.new-notice {
  .mce-statusbar.mce-container.mce-panel.mce-stack-layout-item.mce-last {
    display: none;
  }

  .mce-tinymce.mce-container.mce-panel[role="application"]
    > div
    > div:first-child
    > div
    > div:first-child {
    display: none;
  }

  .mce-tinymce.mce-container.mce-panel[role="application"]
    > div
    > div:first-child
    > div
    > div:last-child
    > div
    > div:first-child {
    display: none;
  }

  .notice-content {
    .el-form-item__content {
      width: calc(100% - 100px);
    }
  }

  #d1_ifr {
    height: 250px !important;
  }

  .new-notice-c {
    margin-top: 30px;
    max-width: 800px;
  }
  .publishFrom_ {
    width: 240px;
    height: 135px;
    border: 1px solid #ddd;
    position: relative;

    .avatar-uploader {
      height: 100%;
    }
    .el-upload--text {
      width: 100%;
      height: 100%;
    }
    .uploader {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(255, 255, 255, 0.1);
    }
    .uploader-list {
      top: 45px;
    }
    .uploader-file {
      height: initial;
      line-height: initial;
      border: 0;
      // background:$bg_5;
      border-radius: 100px;
    }
    .uploader-file-progress {
      background: #338efc;
    }
    .uploader-file-info {
      > div {
        display: inline-block;
        line-height: 20px;
        vertical-align: middle;
        width: auto;
        margin-right: 20px;
        text-align: center;
        float: initial;
        color: #666;
      }
      .uploader-file-name {
        display: block;
        width: 100%;
        margin: 0;
        margin-bottom: 15px;
        display: none;
      }
      span {
        margin-top: 0;
        &:last-of-type {
          margin: 0;
        }
      }
      .uploader-file-actions {
        margin: 0;
      }
    }
    .uploader-file-icon {
      margin: 0;
      margin-right: 10px;
    }
    .uploader-file-status,
    .uploader-file-size,
    .uploader-file-name {
      text-indent: 0;
    }
    .uploader-btn {
      display: block;
      position: relative;
      padding: 0;
      font-size: 100%;
      border: 0;
      background: none;
      height: 100%;
      line-height: 134px;
      text-align: center;
      &:hover {
        // background:$bg_5;
      }
    }
  }

  .numberWord {
    position: absolute;
    bottom: 5px;
    right: 15px;
    color: #999999;
    line-height: 19px;
  }

  .publishFrom_seleck {
    text-align: center;
    text-align-last: justify;
    > .el-form-item {
      text-align: left;
      text-align-last: initial;
      display: inline-block;
      vertical-align: top;
    }
  }
  .publishFrom_b {
    > p {
      color: #999;
      margin: 0;
      line-height: 20px;
      font-size: 12px;
    }
    text-align: center;
    .el-icon-picture {
      font-size: 80px;
      color: #eee;
    }
  }
  .page-mb {
    .el-input-number {
      margin-right: 20px;
    }
  }
  .buttonCSS {
    margin-top: 80px;
  }

  .category-tip {
    font-size: 12px;
    > span {
      color: #999;
    }
    a {
      padding: 0 8px;
      border-radius: 3px;
      color: #409eff;
      display: inline-block;
      vertical-align: top;
      border: 1px solid #409eff;
    }
  }
}
</style>